package com.neulogistics.core.customercenter.api.application.query;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neulogistics.core.customercenter.api.application.converter.OrderPOVMConverter;
import com.neulogistics.core.customercenter.api.application.converter.OrderQueryPOConverter;
import com.neulogistics.core.customercenter.api.application.viewmodel.OrderViewModel;
import com.neulogistics.core.customercenter.infrastructure.persistence.orm.po.OrderPO;
import com.neulogistics.core.customercenter.infrastructure.persistence.orm.service.IOrderPOService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderQueryService implements IOrderQueryService {
    @Resource
    IOrderPOService orderPOService;

    @Override
    public OrderViewModel getOrderById(Long id) {
        OrderPO orderPO = orderPOService.getById(id);
        OrderViewModel orderViewModel = OrderPOVMConverter.POToVM(orderPO);
        return orderViewModel;
    }

    @Override
    public Page<OrderViewModel> page(OrderQuery orderQuery) {
        // 取出条件
        OrderPO orderPOQuery = OrderQueryPOConverter.queryToPO(orderQuery);
        long current = orderQuery.getPageNum();
        long pageSize = orderQuery.getPageSize();

        // 查询
        LambdaQueryWrapper<OrderPO> queryWrapper = new LambdaQueryWrapper<>(orderPOQuery);
        if(orderQuery.orderStatus != null &&orderQuery.orderStatus.length >= 1 && orderQuery.orderStatus[0] != -1){
            ArrayList<Integer> status = new ArrayList<>(orderQuery.orderStatus.length);
            for (int i : orderQuery.orderStatus){
                status.add(i);
            }
            queryWrapper.in(OrderPO::getOrderStatus, status);
        }
        Page<OrderPO> page = orderPOService.page(new Page<>(current, pageSize), queryWrapper);

        // 构造结果
        Page<OrderViewModel> viewModelPage = new Page<>(current, pageSize);
        List<OrderViewModel> viewModelList = page.getRecords().stream()
                .map(OrderPOVMConverter::POToVM).collect(Collectors.toList());
        viewModelPage.setRecords(viewModelList);
        viewModelPage.setTotal(page.getTotal());

        return viewModelPage;
    }


}
